package top.itaso.app.ui.mediaplayer

import android.os.Bundle
import android.util.Log
import android.view.*
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import top.itaso.app.R

class MediaPlayerFragment : Fragment() {

    companion object {
        private const val TAG = "MediaPlayerFragment"
        fun newInstance() = MediaPlayerFragment()
    }

    private lateinit var viewModel: MediaPlayerViewModel
    private lateinit var svMediaPlayer: SurfaceView

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val rootView = inflater.inflate(R.layout.fragment_mediaplayer, container, false)
        initView(rootView)

        return rootView
    }


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel = ViewModelProvider(this).get(MediaPlayerViewModel()::class.java)
        // TODO: Use the ViewModel
    }

    override fun onDestroyView() {
        super.onDestroyView()
        viewModel.stopMediaSource()
    }

    private fun initView(rootView: View) {
        svMediaPlayer = rootView.findViewById(R.id.sv_mediaplayer)
        svMediaPlayer.holder.addCallback(callback)
    }

    private val callback: SurfaceHolder.Callback = object : SurfaceHolder.Callback {
        override fun surfaceCreated(holder: SurfaceHolder) {
            Log.d(TAG, "surfaceCreated: >>>>>>holder=$holder")
            viewModel.initMediaPlayer(svMediaPlayer.holder)
            viewModel.playMediaSource()
        }

        override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
            Log.d(
                TAG,
                "surfaceChanged: >>>>>>format=$format,width=$width,height=$height,holder=$holder"
            )
        }

        override fun surfaceDestroyed(holder: SurfaceHolder) {
            Log.d(TAG, "surfaceDestroyed: >>>>>>holder=$holder")
            viewModel.stopMediaSource()
        }
    }
}